<template>
  <div id="loginView" style="height: 100%; width: 100%">
    <div style="height: 50px; padding: 10px 10px">
      <van-icon size="24px" name="setting-o" @click="go_setting" />
    </div>
    <div class="logo_div">
      <p>库位管理系统</p>
    </div>
    <van-form ref="formRef" class="login_form" :model="ruleForm" @submit="doLogin">
      <div class="login_input">
        <van-cell-group inset>
          <van-field v-model="ruleForm.user" label="用户" left-icon="user-o" placeholder="请输入用户名" :rules="[{ required: true, message: '请输入账号' }]" />
          <van-field v-model="ruleForm.password" type="password" label="密码" left-icon="shield-o" placeholder="请输入密码" :rules="[{ required: true, message: '请输入密码' }]" />
          <van-cell title="保存密码">
            <template #right-icon>
              <van-checkbox v-model="remanber_me"></van-checkbox>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      <div class="login_button">
        <van-button type="primary" size="large" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <van-overlay :show="loading">
      <div class="loading_wrapper"><van-loading type="spinner" size="24" /></div
    ></van-overlay>
  </div>
</template>
<script setup lang="ts">
import { login } from '@/api/user';
import { useUserStore } from '@/stores/userInfo';
import { setValue, getValue, STORAGE_KEY } from '@/utils/localStorage';
import { showSuccessToast, type FormInstance } from 'vant';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const formRef = ref<FormInstance>();
const remanber_me = ref(true);
const ruleForm = reactive({
  user: getValue(STORAGE_KEY.MY_USERCODE) || '',
  password: getValue(STORAGE_KEY.MY_PASSWORD) || '',
});
const loading = ref<boolean>(false);
const doLogin = () => {
  loading.value = true;
  login(ruleForm)
    .then((r) => {
      const store = useUserStore();
      store.set_online_user(r.Data![0]);
      if (remanber_me.value) {
        setValue(STORAGE_KEY.MY_USERCODE, ruleForm.user);
        setValue(STORAGE_KEY.MY_PASSWORD, ruleForm.password);
      }
      loading.value = false;
      showSuccessToast('登录成功');
      router.push('/menu');
    })
    .catch((e) => {
      loading.value = false;
    });
};
const go_setting = () => {
  router.push('/setting');
};
</script>
<style scoped>
.logo_div {
  font-size: xx-large;
  height: calc(100% - 300px - 50px);
  text-align: center;
  padding-top: 80px;
  color: #546b95;
}
.login_form {
  height: 300px;
  width: 100%;
}
.login_input {
  width: 100%;
  height: 165px;
}
.login_button {
  margin-top: 10px;
  width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}
</style>
